<?php

namespace App\Http\Controllers\Rank;

use App\Models\Repository;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UserRepositoriesCount extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        $users = DB::table('repositories')->select(DB::raw('users.name,count(repositories.user_id) as repositories_count'))->join('users', 'users.id', '=', 'repositories.user_id')->whereNotNull('repositories.user_id')->groupBy('repositories.user_id')->orderByDesc('repositories_count')->limit(5)->get()->map(function (
            $item
        ) {
            return [$item->name, $item->repositories_count.'部'];
        });

        return view('resources.rank.user-repositories-count')->with('users', $users);
    }
}
